using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using System.Text;
using 高校员工餐饮信息管理系统.Configuration;
using 高校员工餐饮信息管理系统.Middleware;
using 高校员工餐饮信息管理系统.Services;

// 配置Serilog日志
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

try
{
    Log.Information("========================================");
    Log.Information("高校员工餐饮信息管理系统启动中...");
    Log.Information("========================================");

    var builder = WebApplication.CreateBuilder(args);

    // 使用Serilog作为日志提供程序
    builder.Host.UseSerilog();

    // ============================================
    // 1. 配置应用程序配置管理
    // ============================================
    
    // 读取JWT配置
    var jwtSettings = builder.Configuration.GetSection("Jwt");
    builder.Services.Configure<JwtSettings>(jwtSettings);
    
    // 读取邮件配置
    var emailSettings = builder.Configuration.GetSection("EmailSettings");
    builder.Services.Configure<EmailSettings>(emailSettings);
    
    Log.Information("配置文件加载完成");
    Log.Information("数据库连接: {ConnectionString}", 
        builder.Configuration.GetConnectionString("DefaultConnection"));

    // ============================================
    // 2. 配置身份验证（JWT Bearer）
    // ============================================
    
    var jwtSecret = builder.Configuration["Jwt:Secret"];
    var jwtIssuer = builder.Configuration["Jwt:Issuer"];
    var jwtAudience = builder.Configuration["Jwt:Audience"];

    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret!)),
            ValidateIssuer = true,
            ValidIssuer = jwtIssuer,
            ValidateAudience = true,
            ValidAudience = jwtAudience,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };
    });

    builder.Services.AddAuthorization();

    Log.Information("JWT身份验证配置完成");

    // ============================================
    // 3. 配置依赖注入
    // ============================================
    
    // 注册用户服务
    builder.Services.AddScoped<IUserService, UserService>();
    Log.Information("已注册服务: IUserService -> UserService");
    
    // 注册商户服务
    builder.Services.AddScoped<IMerchantService, MerchantService>();
    Log.Information("已注册服务: IMerchantService -> MerchantService");
    
    // 注册订单服务
    builder.Services.AddScoped<IOrderService, OrderService>();
    Log.Information("已注册服务: IOrderService -> OrderService");
    
    // 注册邮件服务
    builder.Services.AddScoped<IEmailService, EmailService>();
    Log.Information("已注册服务: IEmailService -> EmailService");
    
    // 注册JWT服务
    builder.Services.AddScoped<IJwtService, JwtService>();
    Log.Information("已注册服务: IJwtService -> JwtService");

    // 添加Razor Pages和Controllers支持
    builder.Services.AddRazorPages();
    builder.Services.AddControllers();

    Log.Information("所有服务注册完成");

    // ============================================
    // 4. 构建应用程序
    // ============================================
    
    var app = builder.Build();

    Log.Information("应用程序构建完成，开始配置中间件管道...");

    // ============================================
    // 5. 配置中间件管道
    // ============================================
    
    // 5.1 异常处理中间件（必须在最前面）
    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        Log.Information("开发环境：启用详细错误页面");
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
        Log.Information("生产环境：启用全局异常处理器");
    }

    // 5.2 HTTPS重定向
    app.UseHttpsRedirection();

    // 5.3 静态文件中间件（用于托管CSS、JS、图片等）
    app.UseStaticFiles();
    Log.Information("静态文件中间件已启用：wwwroot目录");

    // 5.4 路由中间件
    app.UseRouting();

    // 5.5 自定义日志记录中间件
    app.UseMiddleware<RequestLoggingMiddleware>();
    Log.Information("自定义中间件已启用：RequestLoggingMiddleware（请求日志记录）");

    // 5.6 身份验证中间件（必须在授权之前）
    app.UseAuthentication();
    Log.Information("身份验证中间件已启用：JWT Bearer认证");

    // 5.7 授权中间件
    app.UseAuthorization();
    Log.Information("授权中间件已启用");

    // 5.8 自定义权限校验中间件（必须在身份验证之后）
    app.UseMiddleware<RolePermissionMiddleware>();
    Log.Information("自定义中间件已启用：RolePermissionMiddleware（角色权限校验）");

    // 5.9 端点映射
    app.MapRazorPages();
    app.MapControllers();

    Log.Information("========================================");
    Log.Information("中间件管道配置完成");
    Log.Information("应用程序运行环境: {Environment}", app.Environment.EnvironmentName);
    Log.Information("应用程序准备就绪，开始监听请求...");
    Log.Information("========================================");

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "应用程序启动失败");
}
finally
{
    Log.CloseAndFlush();
}
